package com.lsh.service.impl;

import com.lsh.dao.ArticleDao;
import com.lsh.dao.UserDao;
import com.lsh.dao.UserHeadPortraitDao;
import com.lsh.dao.UserTokenDao;
import com.lsh.domain.Article;
import com.lsh.domain.ArticlePage;
import com.lsh.service.ArticleService;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.ibatis.javassist.compiler.ast.Keyword;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

@Service
@CacheConfig(cacheNames = "article")
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    ArticleDao articleDao;
    @Autowired
    UserHeadPortraitDao headPortraitDao;
    @Autowired
    UserTokenDao userTokenDao;
    @Autowired
    UserDao userDao;

    /**
     * 展示文章list
     * @return
     */
    @Override
    public List findArticleList() {
        List<LinkedHashMap<String, Object>> articleList = articleDao.getArticleList();
        return articleList;
    }

    /**
     * 获取markdown页面需要的数据
     * @param userId
     * @param artId
     * @return
     */
    @Override
    public Map findOpenMarkdownList(int userId, String artId) {
        Map<String, Object>  map =   null;
        if(artId == null){
            String headUrl = headPortraitDao.getURL(userId);
            map = new HashMap();
            map.put("head_url", headUrl);
        }else{
            map = articleDao.getArticleToHead(userId, Integer.parseInt(artId));
            String content = (String) map.get("content");
        }
        return map;
    }

    /**
     * 获取指定文章详细信息
     * @param username
     * @param artId
     * @return
     */
    @Override
    @Cacheable(key = "'detail_' + #username + '_' + #artId")
    public Map findArticleDetail(String username, String artId){
        Map<String, Object> article = articleDao.getArticleDetail(username, artId);
        int userId = userDao.getUserId(username);
        LinkedHashMap<String, Object> articlePrev = articleDao.getArticlePrev(userId, artId);
        article.put("article_prev", articlePrev);
        LinkedHashMap<String, Object> articleNext = articleDao.getArticleNext(userId, artId);
        article.put("article_next", articleNext);
        return article;
    }

    /**
     * 发布文章
     * @param article
     * @return
     */
    @Override
    public String publishArticle(Article article, String token) {
        String resultMessage = null; //回调参数:文本提示
        String userId = userTokenDao.getByToken(token);
        article.setUid(Integer.parseInt(userId));
        article.setDraft(1);
        Integer artId = article.getArtId();
        if(artId == null){
            int result = articleDao.saveArticle(article);
            resultMessage = (result != 0) ? "发布成功" : "发布失败";
        }else{
            int res = articleDao.updateArticle(article);
            resultMessage = (res != 0) ? "发布成功" : "发布失败";
        }
        return resultMessage;
    }

    /**
     * 保存草稿
     * @param article
     * @return
     */
    @Override
    public Map saveArticle(Article article, String token) {
        String resultMessage = null; //回调参数:文本提示
        String userId = userTokenDao.getByToken(token);
        article.setUid(Integer.parseInt(userId));
        article.setDraft(0);
        int result = articleDao.saveArticle(article);
        resultMessage = (result != 0) ? "草稿已保存" : "草稿保存失败";
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("art_id", article.getArtId());
        map.put("resultMsg", resultMessage);
        return map;
    }

    /**
     * 文章管理首页
     * @param token
     * @return
     */
    @Override
    public Map articleIndex(String token) {
        String userId = userTokenDao.getByToken(token);
        List articleYear = articleDao.getArticleYear(userId);
        List articleMonth = articleDao.getArticleMonth(userId);
        Map map = new HashMap();
        map.put("year", articleYear);
        map.put("month", articleMonth);
        return map;
    }

    /**
     * 分页-文章管理【全部/条件查询】
     * @param token
     * @param page
     * @return
     */
    @Override
    public String findAllArticlePage(String token, int page, ArticlePage articlePage) throws UnsupportedEncodingException {
        String userId = userTokenDao.getByToken(token);
        int rowPage = 4; //读取数据的最大条数
        int lim = (page - 1) * rowPage; //根据页码值表示从数据表第几个数据开始读取
        String keyword = articlePage.getKeyword();
        if(keyword != null && !"".equals(keyword)) articlePage.setKeyword(URLDecoder.decode(keyword, "UTF-8"));
        List<LinkedHashMap<String, Object>> articleList = articleDao.getAllArticlePage(userId, lim, rowPage, articlePage);
        int articleCount = articleDao.getAllArticleCount(userId, 1, articlePage);
        int totalPage = articleCount / rowPage;
        if(articleCount % rowPage != 0) totalPage++; //实际总页数
        String username = userDao.getUsername(Integer.parseInt(userId));
        JSONObject jo = new JSONObject();
        jo.put("current_page", page);
        jo.put("total_page", totalPage);
        jo.put("username", username);
        jo.put("articles", articleList);
        return jo.toString();
    }

    /**
     * 分页-文章管理【草稿箱】
     * @param token
     * @param page
     * @return
     */
    @Override
    public String findDraftsArticlePage(String token, int page){
        String userId = userTokenDao.getByToken(token);
        int rowPage = 7; //读取数据的最大条数
        int lim = (page - 1) * rowPage; //根据页码值表示从数据表第几个数据开始读取
        List<LinkedHashMap<String, Object>> articleList = articleDao.getDraftsArticlePage(userId, lim, rowPage);
        int articleCount = articleDao.getDraftsArticleCount(userId, 0);
        int totalPage = articleCount / rowPage;
        if(articleCount % rowPage != 0) totalPage++; //实际总页数
        JSONObject jo = new JSONObject();
        jo.put("current_page", page);
        jo.put("total_page", totalPage);
        jo.put("articles", articleList);
        return jo.toString();
    }

    /**
     * 文章管理-删除发布文章
     * @param token
     * @param artId
     * @return
     */
    @Override
    public String deleteArticle(String token, String artId, int draft) {
        String code, message;
        String userId = userTokenDao.getByToken(token);
        int row = articleDao.deleteArticle(artId, userId, draft);
        if(row == 1){
            code = "200";
            message = "删除成功";
        }else{
            code = "400";
            message = "删除失败";
        }
        JSONObject jo = new JSONObject();
        jo.put("code", code);
        jo.put("message", message);
        return jo.toString();
    }


}
